<template>
  <div class="orgTree">
    <van-collapse v-model="activeNames" :border="false">
      <van-collapse-item
        :name="item.orgName"
        v-for="item in treeData"
        :key="item.orgName"
      >
        <template #icon v-if="item.orgName">
          <van-icon name="arrow" class="icon" @click="clickItem(item)"/>
        </template>
        <template #title v-if="item.orgName">
          <span @click="clickItem(item)" class="title">{{ item.orgName }}</span>
        </template>
        <template #title v-else>
          <van-radio-group v-model="checked">
            <van-cell-group inset>
              <van-cell
                :title="item.name"
                clickable
                @click="checkedFn(item)"
                class="personName"
              >
                <van-radio :name="item.name" />
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </template>
        <OrgTree
          v-if="item.children"
          :tree-data="item.children"
          @clickItem="emits('clickItem', $event)"
        />
      </van-collapse-item>
    </van-collapse>
  </div>
</template>
<script setup name="OrgTree">
import { ref, watch } from "vue";
import { useStore } from "@/store";
const store = useStore();
defineProps({
  treeData: {
    type: Array,
    default: () => [],
  },
});
const emits = defineEmits(["clickItem", "changeRadio", "clickTree"]);
const checked = ref("");
const activeNames = ref([]);

const clickItem = (item) => {
  emits("clickItem", item); //事件依然采用emits向上触发事件
};

const checkedFn = (item) => {
  store.commit("setOrg/changeOrg", item.name);
  store.commit("setOrg/changeId", item.personId);
  setTimeout(() => {
    checked.value = item.name;
  }, 50);
};

watch(
  () => store.getters["setOrg/getOrg"],
  (nw) => {
    checked.value = undefined;
  }
);
</script>
<style lang="less" scoped>
:deep(.van-collapse-item__content) {
  padding-top: 0;
  padding-bottom: 0;
}
:deep(.van-cell) {
  padding: 13px 0;
  border-bottom: 0.5px solid #e1e5ea;
}
:deep(.van-collapse-item__title--expanded) {
  .van-icon-arrow {
    transform: rotate(90deg);
  }
}

.orgTree {
  /deep/ .van-cell__title {
    display: flex;
  }
  .title {
    flex: 1;
    margin-left: 2px;
  }
  .personName {
    padding-left: 31px !important;
  }
}
.icon {
  padding: 5px;
}
/deep/ .van-radio-group {
  width: 100%;
  .van-radio {
    flex-direction: row-reverse;
  }
}
/deep/ .van-collapse-item__wrapper {
  .icon {
    padding-left: 11px;
  }
}
</style>
